package net.wicp.tams.duckula.server.connector;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.connector.beans.CusDynaBean;
import net.wicp.tams.common.connector.executor.IBusiApp;
import net.wicp.tams.commons.Conf;
import net.wicp.tams.commons.Result;
import net.wicp.tams.commons.apiext.IOUtil;
import net.wicp.tams.commons.apiext.StringUtil;
import net.wicp.tams.commons.exception.ExceptAll;
import net.wicp.tams.commons.thread.ThreadPool;

@Service(value = "TaskStart")
@Slf4j
public class TaskStart implements IBusiApp {
	@Override
	public CusDynaBean exe(CusDynaBean inputBean, CusDynaBean outBeanOri) {
		long begintime = System.currentTimeMillis();
		String taskId = inputBean.getStrValueByName("taskId");
		int jmxPort = Integer.parseInt(inputBean.getStrValueByName("jmxPort"));
		String debugPort = inputBean.getStrValueByName("debugPort");
		String homePath = System.getenv().get("DUCKULA_HOME");
		String cmd = IOUtil.mergeFolderAndFilePath(homePath, "/bin/run.sh");
		String cmdtrue = "";
		if (StringUtil.isNull(debugPort)) {
			cmdtrue = String.format("sh %s %s %s", cmd, taskId, jmxPort);
		} else {
			cmdtrue = String.format("sh %s %s %s %s", cmd, taskId, jmxPort, debugPort);
		}
		log.info("start cmd:{}", cmdtrue);
		try {
			final Process ps = Runtime.getRuntime().exec(cmdtrue);
			ps.waitFor();
			// String instr = IOUtil.slurp(ps.getInputStream(),
			// Conf.getSystemEncode());//会无限等待
			Future<String> query = (Future<String>) ThreadPool.getDefaultPool().submit(new Callable<String>() {
				@Override
				public String call() throws Exception {
					String errstr = IOUtil.slurp(ps.getErrorStream(), Conf.getSystemEncode());
					return errstr;
				}
			});
			try {
				String retstr = query.get(10, TimeUnit.SECONDS);
				log.error("启动失败,原因:[{}]", retstr);
				outBeanOri.setResult(ExceptAll.project_runshell, retstr);
			} catch (ExecutionException e) {
				log.info("超时获得错误流，意味着命令没问题");
				outBeanOri.setResult(ExceptAll.no);
			} catch (TimeoutException e) {
				log.info("超时获得错误流，意味着命令没问题");
				outBeanOri.setResult(ExceptAll.no);
			}

		} catch (IOException ioe) {
			log.error("IO异常，文件有误", ioe);
			outBeanOri.setResult(Result.getError("IO异常，文件有误"));
		} catch (InterruptedException e) {
			log.error("中断异常", e);
			outBeanOri.setResult(Result.getError("中断异常"));
		}
		outBeanOri.set("usetimes", String.valueOf(System.currentTimeMillis() - begintime));
		return outBeanOri;
	}
}
